package py.patch.copy;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import py.patch.util.ReadUtil;

public class FileCopy {
	private String fileName;
	private String targetDir;
	private String srcDir;

	public FileCopy() {
	}

	public FileCopy(String fileName, String targetDir) {
		super();
		this.fileName = fileName;
		this.targetDir = targetDir;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getTargetDir() {
		return targetDir;
	}

	public void setTargetDir(String targetDir) {
		this.targetDir = targetDir;
	}

	public void setSrcDir(String srcDir) {
		this.srcDir = srcDir;
	}

	public String getSrcDir() {
		return srcDir;
	}

	public void copyFile() throws Exception {

		Map<Integer, String> map = ReadUtil.readFileByLines(this.fileName);

		if (map != null && map.size() > 0) {
			for (Iterator iterator = map.keySet().iterator(); iterator
					.hasNext();) {
				Integer key = (Integer) iterator.next();

				String value = map.get(key);
				value = this.replacePath(value);
				this.srcDir = this.replacePath(this.srcDir);
				this.targetDir = this.replacePath(this.targetDir);

				int srcIndex = value.indexOf(this.srcDir);
				if (srcIndex == 0) {
					srcIndex = this.srcDir.length();
				}
				String suffixStr = value.substring(srcIndex);
				String targetFullPath = this.targetDir + suffixStr;

				ReadUtil.copyFile(map.get(key), targetFullPath);
			}
		}

	}

	public void copyFile(List<String> files) throws Exception {

		for (String file : files) {

			String value = this.replacePath(file);
			this.srcDir = this.replacePath(this.srcDir);
			this.targetDir = this.replacePath(this.targetDir);

			int srcIndex = value.indexOf(this.srcDir);
			if (srcIndex == 0) {
				srcIndex = this.srcDir.length();
			}
			String suffixStr = value.substring(srcIndex);
			String targetFullPath = this.targetDir + suffixStr;

			ReadUtil.copyFile(file, targetFullPath);
		}
	}

	public String replacePath(String src) {
		if (StringUtils.isNotEmpty(src)) {
			return src.replace("/", File.separator).replace("\\",
					File.separator);
		} else {
			return "";
		}
	}

}
